import json
from django.core.cache import cache as mem_cache
from celery import shared_task
from celery.task import periodic_task
from django import template
from stocksys import models as stocksys_models
from Library_WEB import settings
from stocksys.sys_tasks.logic_function import DjangoTask, get_realtime_stock_content, workDay, stock_report
from stocksys.views.data_logic import send_email_message





@periodic_task(run_every=10)
def alert_speed():
    '''
    在低位时警报此函数仅用于手动操作警报
    :return:
    '''
    if workDay():
        # mem_cache=memcache.Client(['127.0.0.1:11211'],debug=True)
        mystocks = stocksys_models.MyStcock.objects.all()
        # 自动去寻找和广播所有用户的自选股
        for mystock in mystocks:
            _stock = mystock.stock
            stock_code = "%s%s" % (_stock.stock.exchange_address.stock_sina_name, _stock.stock.code)
            try:
                # 通过新浪API获取实时数据
                stock = get_realtime_stock_content(stock_code)
            #     如果今日开盘价大于昨日收盘价 先拉一次回撤警报 否则买入
            except Exception as e:
                print("%s %s请求异常，跳过" % (stock_code, str(e)))
                continue

            stock['code'] = _stock.stock.code
            # 注意这里close是昨日开盘 open是今日开盘

            # 求当前涨跌幅
            stock_chg = 0
            if float(stock['close']) != 0:
                
                stock_chg = (float(stock['current']) - float(stock['close'])) / float(stock['close']) * 100
            # 当日最低价
            stock_high = stock['high']
            # 当日最低价
            stock_low = stock['low']

            stock['chg'] = stock_chg
            stock['color'] = 'red' if stock['chg'] > 0 else 'green'

            # 判断是否在缓存中
            # 在缓存中，说明股票下拉那么如果现在的价格大于当日最低价的1% 拉响警报
            if mem_cache.get(stock_code):
                pre_stock = json.loads(mem_cache.get(stock_code))
                if stock['current'] != 0:
                    now_chg = (stock['current'] - pre_stock['current']) / stock['current'] * 100
                    if now_chg > 0.3 and stock_chg > 0.1:
                        print("股票%s%s 当前%s 昨收%s 今开%s 涨跌幅%s 最高%s 最低%s 当前差%s" % (
                            stock['code'], stock['name'], stock['current'], stock['close'], stock['open'],
                            stock_chg, stock_high, stock_low, now_chg)
                              )
                        # 生成报告
                        stock = stock_report(_stock, stock)
                        with open(settings.BASE_DIR + "/templates/stocksys/message/急速拉升.html") as template_file:
                            tpl = template.Template(template_file.read())
                            stock['addr'] = stock_code
                            context = template.Context({'stock': stock})
                            content = tpl.render(context)
                            to_user = mystock.sysconf.user
                            title = "%s-%s 当日最低点急速拉升提醒" % (stock['name'], stock_code)
                            send_email_message(title, content, [to_user.email], "HTML")

                    mem_cache.set(stock_code, json.dumps(stock))
            # 如果不在缓存中
            # 当前价格是当日最低价且要低于昨日收盘价，那么进入CACHE等待拉高
            # 如果当前价格比今日开盘价低，那么进入缓存
            else:
                if stock['current'] < stock['open']:
                    print("股票%s%s 当前%s 昨收%s 今开%s 涨跌幅%s 最高%s 最低%s" % (
                        stock['code'], stock['name'], stock['current'], stock['close'], stock['open'],
                        stock_chg, stock_high, stock_low)
                          )
                    print("当前股票下拉，开始监控")
                    mem_cache.set(stock_code, json.dumps(stock))
    else:
        mem_cache.clear()


@shared_task(name="send_email_report")
def async_send_email(title, content, to_email_list, type="TEXT"):
    send_email_message(title, content, to_email_list, type)
